package com.zhangye.test.api;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.zhangye.test.entity.SimilarResult;
import com.zhangye.test.mapper.AdminMoneyMapper;
import com.zhangye.test.model.Admin;
import com.zhangye.test.model.AdminMoney;
import com.zhangye.test.model.ArNavigation;
import com.zhangye.test.model.Category;
import com.zhangye.test.model.EasyAr;
import com.zhangye.test.model.Interview;
import com.zhangye.test.model.Region;
import com.zhangye.test.service.AdminService;
import com.zhangye.test.service.ArNavigationService;
import com.zhangye.test.service.CategoryService;
import com.zhangye.test.service.EasyArService;
import com.zhangye.test.service.InterviewService;
import com.zhangye.test.service.ProxyArService;
import com.zhangye.test.service.ProxyScanCountService;
import com.zhangye.test.service.QiniuService;
import com.zhangye.test.service.RegionService;
import com.zhangye.test.service.SafeSessionService;
import com.zhangye.test.util.AddressUtil;
import com.zhangye.test.util.HttpUtil;
import com.zhangye.test.util.MobileUtils;
import com.zhangye.test.util.PageInfo;
import com.zhangye.test.util.cloudUtils;

/**
 * 添加作品
 * 作者： 张叶
 * 创建时间：2018年7月20日  下午2:31:08
 */
@Controller
@RequestMapping("api/demo")
public class DemoApi {
	
	@Autowired
	private EasyArService easyArService;
	@Autowired
	private InterviewService interViewService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private SafeSessionService safeSessionService;
	@Autowired
	private QiniuService qiniuService;
	@Autowired
	private ProxyArService proxyArService;
	@Autowired
	private ProxyScanCountService proxyScanCountService;
	@Autowired
	private AdminMoneyMapper adminMoneyMapper;

	@Autowired
	private ArNavigationService arNavigationService;
	
	
	/**
	 * 测试
	 * 作者： 张叶
	 * 创建时间：2019年1月15日  上午9:53:08
	 */
	@ResponseBody
	@RequestMapping(value = "/aabbcc")
	public ApiResult aabbcc(String lat,String lng) {
		ApiResult result = new ApiResult();


		Region region = new Region();
		try{
			region = getRegionByLocation(String.format("%s,%s", lng, lat));
		}catch(Exception e){
			region = regionService.getRegionByCode("130101");
		}
		result.data.put("a", region);
		return result;
	}	
	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "/arNavigation")
	public ApiResult listNew(String lat,String lng) {
		ApiResult result = new ApiResult();
		if(lat != null && !"".equals(lat) && lng != null && !"".equals(lng)){
			List<ArNavigation> list = arNavigationService.selectByDisctance(lat, lng);
			if(list.size() > 0){
				Collections.reverse(list);
				result.data.put("ar", list);
				result.msg.status = 0;
				result.msg.desc = "获取成功";
			}else{
				result.msg.status = 1;
				result.msg.desc = "暂无数据";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}	

	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "vvv")
	public ApiResult vvv() {
		ApiResult result = new ApiResult();
		List<EasyAr> list = easyArService.selectAll();
		List<Region> listR = regionService.selectByWhere(" and level = 3");
		Region region = new Region();
		for(EasyAr ea : list){
			region = listR.get(this.random(listR.size()));
			ea.setRegionId(region.getId());
			ea.setRegionCode(region.getCode());
			ea.setRegionName(region.getName());
			easyArService.updates(ea);
		}
		return result;
	}	

	private int random(int max){
		int i = (int) (Math.random() * max);
		return i;
	}

	/**
	 * 视频分类列表
	 * 作者： 张叶
	 * 创建时间：2018年10月30日  下午3:37:39
	 */
	@ResponseBody
	@RequestMapping(value = "/sss")
	public ApiResult sdf() {
		ApiResult result = new ApiResult();
		List<EasyAr> list = easyArService.selectByWhere(" and give is null ");
		for(EasyAr ea : list){
			this.getRand(ea);
			easyArService.updates(ea);
		}
		return result;
	}	
	private EasyAr getRand(EasyAr ea){
		ea.setGive((int) (Math.random() * (200-100) + 100 + 1));
		ea.setShare((int) (Math.random() * (200-100) + 100 + 1));
		ea.setUploadImage((int) (Math.random() * (100-50) + 50 + 1));
		ea.setUploadVideo((int) (Math.random() * (100-50) + 50 + 1));
		ea.setInterviewCount((int) (Math.random() * (1200-600) + 600 + 1));
		return ea;
	}

	

	/**
	 * 视频分类列表
	 * 作者： 张叶
	 * 创建时间：2018年10月30日  下午3:37:39
	 */
	@ResponseBody
	@RequestMapping(value = "/categoryList")
	public ApiResult categoryList(String categoryCode) {
		ApiResult result = new ApiResult();
		if(categoryCode != null && !"".equals(categoryCode)){
			// 搜索条件
			String where = "1 = 1";
			where += " and status = 'on' and category_code like '" + categoryCode + "%'";
			PageInfo pageInfo = new PageInfo();
			if (pageInfo.getPage() < 2
					|| pageInfo.getPage() >= pageInfo.getTotalPage()) {
				pageInfo.setCount(0);
			}
				pageInfo.setPageSize(10);
				pageInfo.setPage(1);
			where += " and (video_url like  '%.mp3%' or video_url like '%.mp4%')";
			List<Map<String, Object>> list = easyArService.selectByPageCategory(pageInfo, where, " order by rand()",null);
			if(list.size() > 0){
				for(int i = 0 ; i < list.size() ; i ++){
					String videoUrl = list.get(i).get("videoUrl").toString();
					videoUrl = videoUrl.split(",")[0];
					list.get(i).put("videoUrl", videoUrl);
				}
				result.data.put("ar", list);
				result.data.put("pageInfo", pageInfo.getTotalPage());
				result.msg.status = 0;
				result.msg.desc = "获取成功";
			}else{
				result.msg.status = 1;
				result.msg.desc = "暂无数据";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}	
	
	
	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "abcc")
	public ApiResult abcc() {
		ApiResult result = new ApiResult();
		List<Admin> list = adminService.selectWhere(" and id not in (select admin_id from admin_money)");
		for(Admin a :list){
			AdminMoney am = new AdminMoney();
			am.setAdminId(a.getId());
			am.setCreatedDate(a.getCreatedate());
			am.setConsumeMoney((double)300);
			am.setMoneyTotal((double)300);
			am.setConsumeDate(new Date());
			am.setType("注册新用户");
			adminMoneyMapper.insert(am);
		}
		return result;
	}	

	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "abcd")
	public ApiResult abcd() {
		ApiResult result = new ApiResult();
		String where = " and (category_code is null or category_code = '')";
		List<EasyAr> list = easyArService.selectByWhere(where);
		for(EasyAr ea : list){
			ea.setCategoryCode("29");
			ea.setCategoryId(69L);
			ea.setCategoryName("推荐");
			easyArService.update(ea);
		}
		return result;
	}	

	
	
	
	
	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "/list")
	public ApiResult list(Integer page, Integer limit) {
		ApiResult result = new ApiResult();

		String where = "1 = 1";
		where += " and status = 'on'";
		PageInfo pageInfo = new PageInfo();
		if (pageInfo.getPage() < 2
				|| pageInfo.getPage() >= pageInfo.getTotalPage()) {
			pageInfo.setCount(0);
		}
		if (limit != null) {// 每页显示条数
			pageInfo.setPageSize(limit);
		}
		if (page != null) {// 当前页
			pageInfo.setPage(page);
		}
		where += " and (video_url like  '%.mp3%' or video_url like '%.mp4%')";
		List<Map<String, Object>> list = easyArService.selectByPageApiNew(pageInfo, where, " order by id desc","38","114",null);
		if(list.size() > 0){
			for(int i = 0 ; i < list.size() ; i ++){
				String videoUrl = list.get(i).get("videoUrl").toString();
				videoUrl = videoUrl.split(",")[0];
				list.get(i).put("videoUrl", videoUrl);
			}
			result.data.put("ar", list);
			result.data.put("pageInfo", pageInfo.getTotalPage());
			result.msg.status = 0;
			result.msg.desc = "获取成功";
		}else{
			result.msg.status = 1;
			result.msg.desc = "暂无数据";
		}
		return result;
	}	

	
	/**
	 * 添加AR
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:39
	 */
	@ResponseBody
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public ApiResult insert(String imageUrl, String videoUrl, String name,
			String info, Long categoryId,Long aId) {
		ApiResult result = new ApiResult();
		
		if(imageUrl != null && !"".equals(imageUrl) 
				&& videoUrl != null && !"".equals(videoUrl)
						&& name != null && !"".equals(name)
								&& info != null && !"".equals(info)){
			Admin admin = adminService.selectByaId(aId);
			if(admin != null && !"".equals(admin)){
				if(imageUrl.getBytes().length < 2097152){
					EasyAr easyar = new EasyAr();
					easyar.setImageUrl(imageUrl);
					easyar.setName(name);
					easyar.setVideoUrl(videoUrl);
					easyar.setAdminId(admin.getId());
					easyar.setCreateAt(new Date());
					easyar.setInfo(info);
					easyar.setType(1);
					String address = getAddress("38.050802", "114.515151");
					easyar.setAddress(address);
					easyar.setAddressLat("38.050802");
					easyar.setAddressLng("114.515151");
					easyar.setStatus("on");
					if(categoryId != null && !"".equals(categoryId)){
						Category category = categoryService.selectByPrimaryKey(categoryId);
						if(category != null && !"".equals(category)){
							easyar.setCategoryId(category.getId());
							easyar.setCategoryCode(category.getCode());
							easyar.setCategoryName(category.getName());
						}
					}
					int i = easyArService.insert(easyar);
					if(i > 0){
						result.msg.status = 0;
						result.msg.desc = "上传成功，审核后方可使用";	
					}else{
						result.msg.status = 1;
						result.msg.desc = "系统错误，上传失败";									
					}
				}else{
					result.msg.status = 9;
					result.msg.desc = "请选择小于2MB的图片";
				}
			}else{
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}
	
	
	/**
	 * 获取经纬度
	 * 作者： 张叶
	 * 创建时间：2018年8月23日  上午9:18:35
	 */
	public String getAddress(String lat, String lng) {
		String region = "";
		try {
			region = AddressUtil.getRegionByLocation(String.format("%s,%s", lng, lat));
		} catch (Exception e) {
			region = "河北省石家庄市";
		}
		return region;
	}
	

	@ResponseBody
	@RequestMapping(value = "/asdf")
	public ApiResult asdf() {
		ApiResult result = new ApiResult();
		String where = " and phone_address = ''";
		List<Admin> list = adminService.selectWhere(where);
		for(Admin admin : list){
			String phoneaddress = MobileUtils.address(admin.getTelphone());
			admin.setPhoneAddress(phoneaddress);
			adminService.updateAdmin(admin, 0);
		}
		return result;
	}
	
	



	/**
	 * 检查图片相似度
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:20
	 */
	@ResponseBody
	@RequestMapping(value = "/aef", method = RequestMethod.POST)
	public ApiResult checkSame1(@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl) {
		ApiResult result = new ApiResult();
		try {
			String a = encode(imageUrl.getBytes());
			String b = image2Base64("https://arvideo.zhyell.com/file/2018/09/21/NNNNNNNTFE5CMu4ZN.jpg");
			SimilarResult sr;
			try {
				sr = cloudUtils.similarCloud(b);
				result.data.put("sr", sr);
				sr = cloudUtils.similarCloud(a);
				result.data.put("old", sr);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
    /**
     * 通过图片的url获取图片的base64字符串
     * @param imgUrl    图片url
     * @return    返回图片base64的字符串
     */
	public static String image2Base64(String imgUrl) {

		URL url = null;
		InputStream is = null;
		ByteArrayOutputStream outStream = null;
		HttpURLConnection httpUrl = null;
		try {
			url = new URL(imgUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			httpUrl.getInputStream();
			is = httpUrl.getInputStream();
			outStream = new ByteArrayOutputStream();
			// 创建一个Buffer字符串
			byte[] buffer = new byte[1024];
			// 每次读取的字符串长度，如果为-1，代表全部读取完毕
			int len = 0;
			// 使用一个输入流从buffer里把数据读取出来
			while ((len = is.read(buffer)) != -1) {
				// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
				outStream.write(buffer, 0, len);
			}
			// 对字节数组Base64编码
			return encode(outStream.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outStream != null) {
				try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpUrl != null) {
				httpUrl.disconnect();
			}
		}
		return imgUrl;
	}

	public static String encode(final byte[] bytes) {  
		return new String(Base64.encodeBase64(bytes));  
	}	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 添加
	 * 作者： 张叶
	 * 创建时间：2018年7月20日  下午2:52:47
	 */
	@ResponseBody
	@RequestMapping(value = "/aaa")
	public ApiResult aaa(){
		ApiResult result = new ApiResult();
		List<EasyAr> list = easyArService.selectByWhere(" and category_id is not null");
		Category c ;
		for(EasyAr ea : list){
			c = categoryService.selectByCode(ea.getCategoryId().toString());
			ea.setCategoryCode(c.getCode());
			ea.setCategoryName(c.getName());
			ea.setCategoryId(c.getId());
			easyArService.update(ea);
		}
		return result;
	}
	

	/**
	 * 添加
	 * 作者： 张叶
	 * 创建时间：2018年7月20日  下午2:52:47
	 */
	@ResponseBody
	@RequestMapping(value = "/insert")
	public ApiResult insert(Long easyArId,int counts){
		ApiResult result = new ApiResult();
		EasyAr ea = easyArService.selectByPrimaryKey(easyArId);
		if(ea != null && !"".equals(ea)){
			Interview iv;
			for(int i = 0 ; i < counts ; i ++){
				iv = new Interview();
				iv.setTelphoneUuid(i + "add");
				iv.setEasyArId(easyArId);
				iv.setCreatedAt(new Date());
				interViewService.insert(iv);
			}
		}
		return result;
	}
	
	/**
	 * 检查图片相似度
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:20
	 */
	@ResponseBody
	@RequestMapping(value = "/checkSame", method = RequestMethod.POST)
	public ApiResult checkSame(@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl) {
		ApiResult result = new ApiResult();
		try {
			result.data.put("leg", imageUrl.getBytes().length);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 检查图片相似度
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:20
	 */
	@ResponseBody
	@RequestMapping(value = "/abc")
	public ApiResult abc() {
		ApiResult result = new ApiResult();
		List<EasyAr> list = easyArService.selectByWhere(" and region_id is null");
		Region region ;
		for(EasyAr ea : list){
			region = new Region();
            region = getRegionByLocation(String.format("%s,%s", ea.getAddressLng(),ea.getAddressLat()));
            if (region == null) {
                region = regionService.getRegionByCode("130101");
            }
            ea.setRegionId(region.getId());
            ea.setRegionCode(region.getCode());
            ea.setRegionName(region.getTitle());
            easyArService.update(ea);
		}
		return result;
	}


	/**
	 * 获取定位信息
	 * 作者： 张叶
	 * 创建时间：2016年11月17日  下午1:48:06
	 */
    public Region getRegionByLocation(String location) {
        List<Region> list = regionService.selectByWhere(" and status = 'on'");
        String key = "ff53d41333699e71213e01ed52a73761";
        String url = String.format("http://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s&poitype=&radius=&extensions=all&batch=false&roadlevel=", key, location);
        String content = HttpUtil.requestGet(url);
        JSONObject json = JSONObject.parseObject(content);
        Region region = null;
        if ("1".equalsIgnoreCase(json.getString("status"))) {//正常
            JSONObject a = json.getJSONObject("regeocode").getJSONObject("addressComponent");

            String district = a.getString("district");
            String adcode = a.getString("adcode");
            String address = json.getJSONObject("regeocode").getString("formatted_address");
            String city = a.getString("city");
            try {//匹配乡镇
                region = list.stream().filter(region1 -> region1.getName().contains(city)).findAny().get();
            } catch (NoSuchElementException e) {
            	
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (region == null) {//匹配城区
                try {
                    region = list.stream().filter(region1 -> 
                    region1.getName().contains(district)).findAny().get();
                } catch (NoSuchElementException e) {
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (region == null) {//未匹配到
                region = new Region();
                region.setLevel(3);
                region.setCode(adcode);
                region.setName(district);
                region.setStatus("on");
                region.setTitle(district);
            }
            if (region.getLevel() == 4) {
                region = regionService.getRegionByCode(region.getCode().substring(0, 6));
            } else if (region.getLevel() == 3) {
            	region = regionService.getRegionByCode(region.getCode());
            } else if (region.getLevel() == 2) {
            	region = regionService.getRegionByCode(region.getCode() + "01");
            }
            region.setRemark(address);
        }
        return region;
    }
}
